package com.cango.student.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class WeakReferenceTest5 {
    public static void main(String[] args) {
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue();
        String value = new String();
        Map<Object, Object> map = new HashMap<>();

        //创建一个线程监听清除的对象
        Thread thread = new Thread(() -> {
            try {
                int cnt = 0;
//                WeakReference<byte[]> k;
                WeakReference<String> k;
                while((k = (WeakReference) referenceQueue.remove()) != null) {
                    System.out.println((cnt++) + "回收了:" + k.get());
                }
            } catch(InterruptedException e) {
                //结束循环
            }
        });
        thread.setDaemon(true);
        thread.start();

        for (int i = 0; i < 1000000; i++) {
//            byte[] bytes = new byte[1024 * 1024];
//            WeakReference<byte[]> weakReference = new WeakReference<>(bytes, referenceQueue);
            WeakReference<String> weakReference = new WeakReference<>(new String("1234567890"), referenceQueue);
            map.put(String.valueOf(i), weakReference);
//            referenceQueue.poll();
//            System.out.println(referenceQueue.poll());

        }
        System.out.println("map.size->" + map.size()); // 有1000个对象
    }
}
